package com.c.ctgproject.ui.login

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.c.ctgproject.entity.UpdateEntity
import com.c.ctgproject.http.ApiMethods
import com.c.ctgproject.utils.MyLog
import com.c.ctgproject.utils.awaitSync
import com.google.gson.Gson
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.lang.Exception

class LoginViewModel : ViewModel() {
    private val _autoLoginEntity: MutableLiveData<String> = MutableLiveData()
    val autoLoginEntity: LiveData<String> get() = _autoLoginEntity
    private val _updateEntity: MutableLiveData<UpdateEntity> = MutableLiveData()
    val updateEntity: LiveData<UpdateEntity> get() = _updateEntity

    //新增错误信息
    private val _errorMsg: MutableLiveData<String> = MutableLiveData()
    val errorMsg: LiveData<String> get() = _errorMsg

    //token登录
    fun tokenLogin(token: String) {

        GlobalScope.launch {
            try {
                val loginResult = ApiMethods.getApiService().loginByToken(token).awaitSync()
                _autoLoginEntity.postValue(loginResult)
            } catch (e: Exception) {
                _errorMsg.postValue(e.message.toString())
            }
        }
    }

    //检查更新
    fun checkUpdate(versionName: String) {
        MyLog.d("上传的版本号:$versionName")
        GlobalScope.launch {
            try {
                val result = ApiMethods.getApiService().checkUpdate(versionName).awaitSync()
                MyLog.d("更新回调$result")
                val entity = Gson().fromJson(result, UpdateEntity::class.java)
                _updateEntity.postValue(entity)
            } catch (e: Exception) {
                _errorMsg.postValue(e.message.toString())
            }
        }
    }
}




